<template>
  <div class="chart-bar-resource-root" ref="ChartBarResourceRef" v-loading="rqLoading"
    element-loading-text="正在查询了流量信息, 请稍后..."></div>
</template>

<script setup lang="ts">
import { ref, onMounted, inject, nextTick } from "vue";
import { resourcesRestfulApi } from '@/api/sentinel';
// echarts
import * as echartTheme from '@/assets/styles/xz/echartTheme';
import * as echarts from 'echarts/core';
import { GridComponent, TooltipComponent } from 'echarts/components';
import { BarChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([TooltipComponent, GridComponent, BarChart, CanvasRenderer, UniversalTransition]);

/* ============================================================
 * inject
 * 用于多层嵌套中使用流量, 下列相关信息使用
 * ============================================================ */
const currentMachine: any = inject('currentMachine');

/* ============================================================
 * props
 * 在单层嵌套中使用的简单的参数
 * ============================================================ */
const props = defineProps({
  interval: { type: String, default: '1d' },
  startTime: { type: String, default: '' },
  endTime: { type: String, default: '' }
})

const rqLoading = ref<boolean>(true);
const ChartBarResourceRef = ref<any>(null);
let chartBarResource: any; // 图表对象
let chartData = {
  resource: [{}],
  value: [{}]
}

const getResourceApi = () => {
  let param = {
    appName: currentMachine.value.appName,
    interval: props.interval,
    startTime: props.startTime,
    endTime: props.endTime
  };

  resourcesRestfulApi(currentMachine.value.appName, param).then(resp => {
    if (resp.data.length > 0) {
      chartData.resource = resp.data
        .filter((item: any) => item.resource !== '__total_inbound_traffic__' && item.resource !== '__cpu_usage__')
        .map((item: any) => {
          return item.resource;
        });

      chartData.value = resp.data
        .filter((item: any) => item.resource !== '__total_inbound_traffic__' && item.resource !== '__cpu_usage__')
        .map((item: any) => {
          let valueAndStyle = {
            resourceName: item.resource,
            value: item.success,
            itemStyle: {},
            avgRt: item.avgRt,
            maxRt: item.maxRt,
            minRt: item.minRt
          };

          if (item.resource.substring(0, 1) === '/') {
            valueAndStyle.itemStyle = { color: echartTheme.clr().green }
          } else {
            valueAndStyle.itemStyle = { color: echartTheme.clr().purple }
          }
          return valueAndStyle;
        });
    }
    renderChart();
  })
}

const renderChart = () => {
  chartBarResource.setOption({
    title: {
      top: 10, right: 0, text: '资源流量排行',
      subtext: '1.非ES存储时为单机流量\n2.非ES存储时请在右上角选择集群',
      textStyle: echartTheme.title().textStyle
    },
    tooltip: {
      ...echartTheme.tooltip(), ...{
        formatter: (params: any) => {
          let data = params[0].data;
          let resourceNameSpan = params[0].name;
          if (resourceNameSpan.substring(0, 1) === '/') {
            resourceNameSpan = "<span style='color:#199818 '>REST：" + resourceNameSpan + "</span>";
          } else {
            resourceNameSpan = "<span style='color:#5745ff '>RPC：" + resourceNameSpan + "</span>";
          }
          return "<div style='text-align: left'>" +
            resourceNameSpan + "<br/>" +
            "请求数：" + data.value + "<br/>" +
            "平均用时：" + data.avgRt + " ms<br/>" +
            "最大用时：" + data.maxRt + " ms<br/>" +
            "最小用时：" + data.minRt + " ms<br/>" +
            "</div>";
        },
        axisPointer: {
          type: 'shadow'
        }
      }
    },
    grid: { top: 10, left: 10, right: 20, bottom: 10, containLabel: true },
    xAxis: [{
      type: 'category',
      // 如果设置了 type 是 'category'，但没有设置 axis.data，则 axis.data 的内容会自动从 series.data 中获取
      data: chartData.resource,
      axisTick: { alignWithLabel: true }
    }],
    yAxis: { splitLine: { lineStyle: { color: echartTheme.common().axisLineColor } } },
    series: [{
      name: '流量',
      type: 'bar',
      barWidth: '60%',
      data: chartData.value,
      showBackground: true,
      backgroundStyle: { color: 'rgba(224,224,224,0.1)' }
    }]
  });
}

const reload = () => {
  nextTick(() => {
    getResourceApi();
  })
}

onMounted(() => {
  chartBarResource = echarts.init(ChartBarResourceRef.value);
  chartBarResource.resize();
})

defineExpose({
  reload
})
</script>

<style scoped lang="scss">
.chart-bar-resource-root {
  @include box(100%, 100%);
}
</style>